angular.module('starter.controllers', [])

.controller('LoginCtrl', function($scope, $state, $ionicLoading, Customer, Storage) {
    var storageKey='user';

    //1 用户登陆
    $scope.user={
        mobile:'',
        password:''
    }
    $scope.signIn=function(){
        if(Customer.checkLogin($scope.user.mobile, $scope.user.password)){
            Customer.login($scope.user.mobile,$scope.user.password);
        }
    }

    $scope.$on('Customer.loginUpdated', function() {

        var userRel = Customer.getCurrentUser();

        if(userRel.code != 0){//登陆失败
            //    alert(userRel.message);
            $ionicLoading.show({
                noBackdrop: true,
                template: userRel.msg,
                duration: 1500
            });
        }else{
            Storage.set(storageKey,userRel.data.customer.id);
            //0 微信公众号授权
            var url = location.host;
            var url_id=encodeURIComponent(location.href.substr(0, location.href.indexOf('#'))+'?m=bill-list');
            location.href = 'http://'+url + '/Home/Pay/getOpenid?uid='+userRel.data.customer.id+'&url='+url_id;
        }
    });
})

.controller('BillList', function($scope, BillListFactory, Storage, ENV) {
    var storageKey='user';
    var customer_id = Storage.get(storageKey);
    $scope.img_url = ENV.img_url;

    //1 获取账单历史信息
    BillListFactory.getBillList(customer_id);

    //2. 发送请求后，接收到刚才传过来的通知
    $scope.$on('onBillList', function(){
        $scope.billList = BillListFactory.returnBillList();
        $scope.hasNextPage = $scope.billList.has_next_page;
        console.log($scope.hasNextPage);
    });

    //下拉更新
    $scope.doRefresh = function(){
        BillListFactory.getBillList(customer_id);
        $scope.$broadcast('scroll.refreshComplete');
    };

    //上拉加载更多
    $scope.loadMore = function(){
        BillListFactory.getMoreBillList(customer_id);
        $scope.$broadcast('scroll.infiniteScrollComplete');
    };

    $scope.payOrder = function(bill){
        BillListFactory.payOrderByConsumeId(bill);
    }
});